package com.tsfyun.scm.service.impl.user;

import com.tsfyun.common.base.exception.ServiceException;
import com.tsfyun.common.base.extension.ServiceImpl;
import com.tsfyun.common.base.util.TsfPreconditions;
import com.tsfyun.scm.entity.user.CustomerPerson;
import com.tsfyun.scm.mapper.user.CustomerPersonMapper;
import com.tsfyun.scm.service.user.ICustomerPersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 *
 * @since 2020-09-15
 */
@Service
public class CustomerPersonServiceImpl extends ServiceImpl<CustomerPerson> implements ICustomerPersonService {

    @Autowired
    private CustomerPersonMapper customerPersonMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bindCustomerPerson(Long customerId, Long personId, Boolean isDefault) {
        CustomerPerson cp = new CustomerPerson();
        cp.setCustomerId(customerId);
        cp.setPersonId(personId);
        cp.setIsDefault(isDefault);
        CustomerPerson existence = super.getOne(cp);
        //不存在绑定关系
        if(Objects.isNull(existence)){
            customerPersonMapper.insert(cp);
        }
        if(cp.getIsDefault()){
            customerPersonMapper.updateCustomerPersonDefault(personId,cp.getId());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void newBindCustomerPerson(Long personId, Long customerId, Long newCustomerId) {
        CustomerPerson customerPerson = customerPersonMapper.findByCustomerIdAndPersonId(customerId,personId);
        TsfPreconditions.checkArgument(Objects.nonNull(customerPerson),new ServiceException("未找到客户与人员对应关系"));
        customerPerson.setCustomerId(newCustomerId);
        customerPerson.setIsDefault(Boolean.TRUE);
        super.updateById(customerPerson);
    }
}
